package com.neu.api.controller.app;


import com.neu.api.dto.CustomerDTO;
import com.neu.api.exception.ParamException;
import com.neu.api.properties.JWTProperties;
import com.neu.api.query.UserQuery;
import com.neu.api.service.CustomerService;
import com.neu.api.utils.JWTUtil;
import com.neu.api.utils.PageResult;
import com.neu.api.utils.Result;
import com.neu.api.utils.StringUtil;
import com.neu.api.vo.CustomerVO;
import com.neu.api.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "顾客接口")
@RestController
@RequestMapping("app/customer")
@Slf4j
public class CustomerController {

    Logger logger = LoggerFactory.getLogger(CustomerController.class);

    @Resource
    JWTProperties jwtProperties;

    @Resource
    CustomerService customerService;


    /**
     * 顾客登录
     * @param phone
     * @param password
     * @return
     */
    @ApiOperation("顾客登录")
    @PostMapping("/login")
    public Result<List<CustomerVO>> Login(@Param("phone") String phone, @Param("password")String password){
        log.info("顾客登录："+"手机号："+phone+",密码："+password);
        //参数的校验
        if(StringUtil.isEmpty(phone) || StringUtil.isEmpty(password)){
            throw new ParamException("账号和密码都不能为空");
        }

        CustomerVO customerVO = customerService.login(phone,password);
        if(customerVO==null){
            return Result.failure("账号或密码错误");
        }

        //服务器生成token --> 响应给前端----->前端每次发请求都携带token------->服务器要校验

        Map<String,Object> payload = new HashMap<>();
        payload.put(JWTUtil.CUSTOMER_ID,customerVO.getId());

        String token = JWTUtil.generateToken(payload,jwtProperties.getSecure(),jwtProperties.getExpire());
        log.info("token："+token);
        Map<String,Object> data = new HashMap<>();
        data.put("token",token);
        data.put("customerInfo",customerVO);
        return Result.ok("成功",data);
    }


    @ApiOperation("注册接口")
    @PostMapping("/register")
    public Result add(CustomerDTO customerDTO){
        logger.info("调用了add方法，查询顾客");
        customerService.add(customerDTO);
        return Result.ok("注册成功!");
    }





    @ApiOperation("编辑接口")
    @PutMapping("/{id}")
    public Result update(@PathVariable Long id,CustomerDTO customerDTO){
        logger.info("调用了update方法，编辑顾客");
        customerService.update(id,customerDTO);
        return Result.ok("修改成功!");
    }

    @ApiOperation("删除接口")
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Long id){
        logger.info("调用了deleteById方法，删除顾客");
        customerService.deleteById(id);
        return Result.ok("删除成功!");
    }

}
